package com.hhxy.servlet;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 测试防止盗链
 * @author ghp
 * @date 2022/9/20
 */
@WebServlet("/preventHotlinkServlet")
public class PreventHotlinkServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter pw = response.getWriter();
        // 获取referer头的值
        String referer = request.getHeader("referer");
        System.out.println(referer);
        // 获取访问地址
        String sitePart = "http://" + request.getServerName();
        // 判断referer头是否为空，这个头的首地址是否以sitePart开始的
        if (referer != null && referer.startsWith(sitePart)) {
            response.setContentType("text/html;charset=utf-8");
            // 处理正在下载的请求
            pw.println("dealing download ...");
        } else {
            //非法下载跳转到download.html页面（）
            RequestDispatcher rd = request.getRequestDispatcher("/html/preventDownload.html");
            rd.forward(request, response);
        }
    }
}